<?php

namespace App\Http\Middleware;

use App\ConstDir\ErrorConst;
use Illuminate\Http\JsonResponse;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Middleware\BaseMiddleware;

/*
 * 前端认证
 */
class FrontAuthenticate extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        if (! $token = $this->auth->setRequest($request)->getToken()) {
            return new JsonResponse([
                'code' => ErrorConst::NOT_LOGIN,
                'message' => ErrorConst::NOT_LOGIN_MSG,
                'data' => null
            ]);
        }

        $user = $this->auth->authenticate($token);
        if (! $user) {
            return $this->respond('tymon.jwt.user_not_found', 'user_not_found', 404);
        }

        $this->events->fire('tymon.jwt.valid', $user);

        return $next($request);
    }
}